package com.zoe.onelink.logging.trace.zipkin.custom;

import com.zoe.onelink.logging.trace.property.OnelinkZipkinProperties;
import com.zoe.onelink.logging.trace.zipkin.interceptor.ZipkinRestTemplateGZipInterceptor;
import com.zoe.onelink.logging.trace.zipkin.interceptor.ZipkinRestTemplateLoggingInterceptor;
import org.springframework.cloud.sleuth.zipkin2.ZipkinProperties;
import org.springframework.cloud.sleuth.zipkin2.ZipkinRestTemplateCustomizer;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-10-10
 */
public class OnelinkZipkinRestTemplateCustomizer implements ZipkinRestTemplateCustomizer {

    private final ZipkinProperties zipkinProperties;
    private final OnelinkZipkinProperties onelinkZipkinProperties;

    public OnelinkZipkinRestTemplateCustomizer(ZipkinProperties zipkinProperties, OnelinkZipkinProperties onelinkZipkinProperties) {
        this.zipkinProperties = zipkinProperties;
        this.onelinkZipkinProperties = onelinkZipkinProperties;
    }

    @Override
    public RestTemplate customizeTemplate(RestTemplate restTemplate) {
        ClientHttpRequestFactory requestFactory = restTemplate.getRequestFactory();
        if (requestFactory instanceof SimpleClientHttpRequestFactory) {
            SimpleClientHttpRequestFactory simpleRequestFactory = (SimpleClientHttpRequestFactory) requestFactory;
            if (onelinkZipkinProperties.getConnectTimeoutMillis() > 0) {
                simpleRequestFactory.setConnectTimeout(onelinkZipkinProperties.getConnectTimeoutMillis());
            }
            if (onelinkZipkinProperties.getReadTimeoutMillis() > 0) {
                simpleRequestFactory.setReadTimeout(onelinkZipkinProperties.getReadTimeoutMillis());
            }
        }
        List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
        if (this.zipkinProperties.getCompression().isEnabled()) {
            interceptors.add(0, new ZipkinRestTemplateGZipInterceptor());
        }
        interceptors.add(new ZipkinRestTemplateLoggingInterceptor(zipkinProperties, onelinkZipkinProperties));
        return restTemplate;
    }

}